package cc.comac.mom.datahandlers.entity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cc.comac.mom.bean.EquipDevHistory;
import cc.comac.mom.bean.EquipRegularCheckWorkOrder;
import cc.comac.mom.bean.EquipRegularCheckWorkOrderBean;
import cc.comac.mom.bean.EquipRegularCheckWorkOrderItem;
import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.dao.entity.EquipDevDao;
import cc.comac.mom.dao.entity.EquipRegularCheckPlanDao;
import cc.comac.mom.dao.entity.EquipRegularCheckWorkOrderDao;
import cc.comac.mom.dao.entity.EquipRegularCheckWorkOrderItemDao;
import cc.comac.mom.dao.entity.EquipReqularCheckItemDao;
import cc.comac.mom.entity.EquipDevEntity;
import cc.comac.mom.entity.EquipDevHistoryEntity;
import cc.comac.mom.entity.EquipRegularCheckPlanEntity;
import cc.comac.mom.entity.EquipRegularCheckWorkOrderEntity;
import cc.comac.mom.entity.EquipRegularCheckWorkOrderItemEntity;
import cc.comac.mom.entity.EquipReqularCheckItemEntity;
import cc.comac.mom.redis.IdFactory;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.MomConstants;
import cc.comac.mom.util.ResultBean;
import cc.comac.mom.util.TimeUtil;

@Component
@Transactional
public class EquipRegularCheckWorkOrderDataHandler
		extends ServiceImpl<EquipRegularCheckWorkOrderDao, EquipRegularCheckWorkOrderEntity> {
	@Autowired
	private EquipRegularCheckWorkOrderDao equipRegularCheckWorkOrderDao;
	
	@Autowired
	private EquipRegularCheckPlanDao equipRegularCheckPlanDao;

	@Autowired
	private EquipRegularCheckWorkOrderItemDataHandler equipRegularCheckWorkOrderItemDataHandler;
	@Resource
	private IdFactory idFactory;

	@Autowired
	private EquipRegularCheckWorkOrderItemDao equipRegularCheckWorkOrderItemDao;

	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;

	@Autowired
	private EquipReqularCheckItemDao EquipReqularCheckItemDao;
	
	@Autowired
	private EquipDevHistoryDataHandler equipDevHistoryDataHandler;

	@Autowired
	private EquipDevDao equipDevDao;

	public ResultBean insertBatch(List<EquipRegularCheckWorkOrder> list) {
		// 222
		ResultBean resultBean = new ResultBean(true);
		if (list == null || list.size() < 1) {
			throw new RuntimeException("数据为空");
		}
		ArrayList<EquipRegularCheckWorkOrderEntity> listEntity = new ArrayList<EquipRegularCheckWorkOrderEntity>();
		ArrayList<EquipRegularCheckWorkOrderItem> listEquipRegularCheckWorkOrderItem = new ArrayList<EquipRegularCheckWorkOrderItem>();
		for (EquipRegularCheckWorkOrder item : list) {
			EquipRegularCheckWorkOrderEntity innerData = item.getInnerData();
			if (innerData == null) {
				throw new RuntimeException("数据为空");
			}
			// 查询计划数据为了后面赋值人员
			EquipRegularCheckPlanEntity selectById = equipRegularCheckPlanDao.selectById(innerData.getEquipCheckPlanId());
			innerData.setId(idFactory.generateId());
			//	entity.setSiteId(idUtil.getSiteId());
			innerData.setCreationTime(TimeUtil.getLocalDateTime());
			innerData.setCreationTimeZone(TimeUtil.getLocalTimeZone());
			innerData.setLastModifiedTime(TimeUtil.getLocalDateTime());
			innerData.setLastModifiedTimeZone(TimeUtil.getLocalTimeZone());
			innerData.setRowStatus(1);
			innerData.setCreator(selectById.getCreator());
			innerData.setLastModifier(selectById.getLastModifier());
//			baseEntityDataUtil.setBaseEntityData(innerData);
			listEntity.add(innerData);
			QueryWrapper<EquipReqularCheckItemEntity> queryWrapper = new QueryWrapper<EquipReqularCheckItemEntity>();
			queryWrapper.eq("row_status", 1);
			queryWrapper.eq("regular_check_id", innerData.getCheckBenchmarkId());
			List<EquipReqularCheckItemEntity> selectList = EquipReqularCheckItemDao.selectList(queryWrapper);
			if (selectList != null && selectList.size() > 0) {
				for (EquipReqularCheckItemEntity item2 : selectList) {
					EquipRegularCheckWorkOrderItem equipRegularCheckWorkOrderItem = new EquipRegularCheckWorkOrderItem();
					EquipRegularCheckWorkOrderItemEntity equipRegularCheckWorkOrderItemEntity = new EquipRegularCheckWorkOrderItemEntity();
					equipRegularCheckWorkOrderItemEntity.setBenchmarkSeq(item2.getBenchmarkSeq());
					equipRegularCheckWorkOrderItemEntity.setRegularCheckOrderId(innerData.getId());
					equipRegularCheckWorkOrderItemEntity.setBenchmarkDevPart(item2.getBenchmarkDevPart());
					equipRegularCheckWorkOrderItemEntity.setItemName(item2.getItemName());
					equipRegularCheckWorkOrderItemEntity.setRecord(item2.getRecord());
					equipRegularCheckWorkOrderItemEntity.setItemStandard(item2.getItemStandard());
					equipRegularCheckWorkOrderItemEntity.setItemMethod(item2.getItemMethod());
					equipRegularCheckWorkOrderItemEntity.setBenchmarkType(item2.getBenchmarkType());
					equipRegularCheckWorkOrderItemEntity.setBenchmarkTime(item2.getBenchmarkTime());
					equipRegularCheckWorkOrderItemEntity.setStandardValue(item2.getStandardValue());
					equipRegularCheckWorkOrderItemEntity.setCreator(selectById.getCreator());
					equipRegularCheckWorkOrderItemEntity.setLastModifier(selectById.getLastModifier());
					equipRegularCheckWorkOrderItem.setInnerData(equipRegularCheckWorkOrderItemEntity);
					listEquipRegularCheckWorkOrderItem.add(equipRegularCheckWorkOrderItem);

				}
			}

		}
		boolean saveBatch = this.saveBatch(listEntity);
		if (!saveBatch) {
			throw new RuntimeException("批量保存计划工单失败");
		}
		ResultBean insertBatch = equipRegularCheckWorkOrderItemDataHandler
				.insertBatch(listEquipRegularCheckWorkOrderItem);
		if (!insertBatch.success) {
			throw new RuntimeException(insertBatch.getMessage());
		}
		return resultBean;
	}

	// 查询
	public ResultDev selectByFields(EquipRegularCheckWorkOrderBean obj) {
		ResultDev resultDev = new ResultDev();
		if (obj.getPageSize() == 0) {
			obj.setPageSize(10);
		}
		obj.setPageNum((obj.getPageNum() - 1) * obj.getPageSize());
		List<EquipRegularCheckWorkOrderBean> listEquipRegularCheckPlanBean = equipRegularCheckWorkOrderDao
				.selectByFields(obj);
		long countByFields = equipRegularCheckWorkOrderDao.selectCountByFields(obj);

		// 将查询总数除以每页数量后向上取整获取总页数
		double pageCount = Math.ceil((double) countByFields / obj.getPageSize());
		resultDev.setEntityList(listEquipRegularCheckPlanBean);
		resultDev.setPageCount((int) pageCount);
		resultDev.setTotalQuantity((int) countByFields);
		return resultDev;
	}

	// 调整日期
	public ResultBean adjustDate(EquipRegularCheckWorkOrder obj) {
		ResultBean resultBean = new ResultBean(true);
		if (obj == null || obj.getInnerData() == null) {
			throw new RuntimeException("数据为空");
		}
		EquipRegularCheckWorkOrderEntity selectById = equipRegularCheckWorkOrderDao
				.selectById(obj.getInnerData().getId());
		if (selectById == null) {
			throw new RuntimeException("数据为空");
		}
		selectById.setPlanStartDate(obj.getInnerData().getPlanStartDate());
		selectById.setPlanEndDate(obj.getInnerData().getPlanEndDate());
		baseEntityDataUtil.updateBaseEntityData(selectById);
		int updateById = equipRegularCheckWorkOrderDao.updateById(selectById);
		if (updateById < 1) {
			throw new RuntimeException("调整日期失败");
		}
		return resultBean;
	}

	// 修改执行用时
	public ResultBean updateExecuteTime(EquipRegularCheckWorkOrder obj) {
		ResultBean resultBean = new ResultBean(true);
		if (obj == null || obj.getInnerData() == null) {
			throw new RuntimeException("数据为空");
		}
		EquipRegularCheckWorkOrderEntity innerData = obj.getInnerData();
		EquipRegularCheckWorkOrderEntity selectById = equipRegularCheckWorkOrderDao.selectById(innerData.getId());
		if (selectById == null) {
			throw new RuntimeException("执行信息不存在");
		}
		if (selectById.getStatus() != MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_EXECUTED) {
			throw new RuntimeException("执行未完成，不能修改");
		}
		selectById.setActualExecuteTime(innerData.getActualExecuteTime());
		baseEntityDataUtil.updateBaseEntityData(selectById);
		int updateById = equipRegularCheckWorkOrderDao.updateById(selectById);
		if (updateById < 1) {
			throw new RuntimeException("调整执行用时失败");
		}
		return resultBean;
	}

	// 开始执行
	public ResultBean planStartExecute(EquipRegularCheckWorkOrder obj) {
		ResultBean resultBean = new ResultBean(true);
		if (obj == null || obj.getInnerData() == null) {
			throw new RuntimeException("数据为空");
		}
		EquipRegularCheckWorkOrderEntity innerData = obj.getInnerData();
		EquipRegularCheckWorkOrderEntity selectById = equipRegularCheckWorkOrderDao.selectById(innerData.getId());
		if (selectById == null) {
			throw new RuntimeException("执行信息不存在");
		}
		if (selectById.getStatus() != MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_NOEXECUTE) {
			throw new RuntimeException("该计划工单已经开始执行，不能再次开始");
		}
		selectById.setFirstExecuteStartDate(new Date());
		selectById.setExecutionUser(baseEntityDataUtil.getCurrentUser());
		selectById.setExecutionUserJobNumber(obj.getInnerData().getExecutionUserJobNumber());
		selectById.setActualExecuteTime(new BigDecimal(0));
		selectById.setStatus(MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_EXECUTEING);
		baseEntityDataUtil.updateBaseEntityData(selectById);
		int updateById = equipRegularCheckWorkOrderDao.updateById(selectById);

		// 工单开始执行时记录设备履历
		EquipDevHistory equipDevHistory = new EquipDevHistory();
		EquipDevHistoryEntity equipDevHistoryEntity = new EquipDevHistoryEntity();
		equipDevHistory.setInnerData(equipDevHistoryEntity);
		// 通过设备编号查询设备信息
		EquipDevEntity selectOne = equipDevDao.selectById(selectById.getDevId());
		equipDevHistoryEntity.setDevId(selectOne.getId());
		equipDevHistoryEntity.setDevNumber(selectOne.getDevNumber());
		equipDevHistoryEntity.setOperationDetail(selectById.getWorkNumber());
		equipDevHistoryEntity.setOperationStyle("点检");
		equipDevHistoryEntity.setRecordTime(new Date());
		equipDevHistoryEntity.setOperator(baseEntityDataUtil.getCurrentUser());
		baseEntityDataUtil.setBaseEntityData(equipDevHistoryEntity);
		equipDevHistoryDataHandler.insertHistory(equipDevHistory);


		if (updateById < 1) {
			resultBean.setErrorMessge("开始执行失败");
			return resultBean;
		}
		return resultBean;
	}

	// 删除批量
	public ResultBean deleteBatch(List<Long> ids) {
		ResultBean resultBean = new ResultBean(true);
		if (ids == null || ids.size() < 1) {
			throw new RuntimeException("数据为空");
		}
		List<EquipRegularCheckWorkOrderEntity> selectBatchIds = equipRegularCheckWorkOrderDao.selectBatchIds(ids);
		if (selectBatchIds == null || selectBatchIds.size() < 1) {
			throw new RuntimeException("数据为空");
		}
		for (EquipRegularCheckWorkOrderEntity item : selectBatchIds) {
			if (item.getStatus() != MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_NOEXECUTE) {
				throw new RuntimeException("工单号:" + item.getWorkNumber() + " 已执行，不可删除");
			}
			baseEntityDataUtil.deleteBaseEntityData(item);
		}
		boolean updateBatchById = this.updateBatchById(selectBatchIds);
		if (!updateBatchById) {
			throw new RuntimeException("批量删除定检计划工单失败");
		}
		// 删除子项
		ArrayList<EquipRegularCheckWorkOrderItemEntity> listItem = new ArrayList<EquipRegularCheckWorkOrderItemEntity>();
		for (EquipRegularCheckWorkOrderEntity item : selectBatchIds) {
			QueryWrapper<EquipRegularCheckWorkOrderItemEntity> queryWrapper = new QueryWrapper<EquipRegularCheckWorkOrderItemEntity>();
			queryWrapper.eq("row_status", 1);
			queryWrapper.eq("regular_check_order_id", item.getId());
			List<EquipRegularCheckWorkOrderItemEntity> list = equipRegularCheckWorkOrderItemDao
					.selectList(queryWrapper);
			if (list != null && list.size() > 0) {
				listItem.addAll(list);
			}
		}
		if (listItem != null && listItem.size() > 0) {
			for (EquipRegularCheckWorkOrderItemEntity item : listItem) {
				baseEntityDataUtil.deleteBaseEntityData(item);
			}
			boolean updateBatchById2 = equipRegularCheckWorkOrderItemDataHandler.updateBatchById(listItem);
			if (!updateBatchById2) {
				throw new RuntimeException("批量删除定检计划工单项失败");
			}
		}
		return resultBean;
	}

}
